package cn.kwq.project_manger.service.impl;

import cn.kwq.project_manger.pojo.QUser;
import cn.kwq.project_manger.pojo.User;
import cn.kwq.project_manger.pojo.dto.WX_Dto;
import cn.kwq.project_manger.repostitory.UserRepository;
import cn.kwq.project_manger.service.UpdateWxMessageService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *不使用
 */
@Service
@Slf4j
@Deprecated
public class UpdateWxMessageServiceImpl implements UpdateWxMessageService {
    @Value("${WeChat.APPID}")
    private  String APPID;
    @Value("${WeChat.SECRET}")
    private String SECRET;
    @Value("${WeChat.GRANT_TYPE}")
    private String GRANT_TYPE;

    @Value("${WeChat.WX_URL}")
    private String WX_URL;

    @Value("${WeChat.WX_USERINFO_URL}")
    private String WX_USERINFO_URL;


    @Autowired
    UserRepository userRepository;

    @Autowired
    JPAQueryFactory jpaQueryFactory;


    /**
     * 根据id来更新微信信息
     * @param code
     * @return
     */
    @Override
    @Transactional(rollbackForClassName = "Exception.class")//出现异常就回滚
    public User UpdateWxMessage(String code,Long id) {
        WX_Dto wxMsg = getWXmsg(code);
        log.info(wxMsg.toString());

        QUser user = QUser.user;

        jpaQueryFactory.update(user)
                .set(user.avatar, wxMsg.getAvatar())
                .set(user.nickName, wxMsg.getNickName())
                .set(user.openid, wxMsg.getOpenid())
                .where(user.id.eq(id))
                //执行更新
                .execute();
        User fetch = jpaQueryFactory.selectFrom(user)
                .where(user.id.eq(id))
                .fetchOne();


        return fetch;
    }



    /**
     * 调用微信api获取openid等信息
     * @param code
     * @return
     */
    private WX_Dto getWXmsg(String code) {
        //DONE:  2022/11/6 17:19 封装请求体
        String param = "appid="+APPID+"&secret="+SECRET+"&code="+code+"&grant_type="+GRANT_TYPE;
        String requsetURL = WX_URL + "?" + param;
        //DONE:  2022/11/6 17:19 获取请求
        String response = HttpRequest.get(requsetURL).body();


        //DONE:  2022/11/6 17:24 json解析为json对
        JSONObject obj = JSON.parseObject(response);

        //获取openid和accsess_token
        String openid = (String)obj.get("openid");
        String accessToken = (String)obj.get("access_token");
        // TODO: 2022/11/10 调试
        log.info("第一步请求json："+response);
        log.info("第一步请求："+"["+"openid: "+openid+"]");
        log.info("第一步请求："+"["+"access_token: "+accessToken+"]");
        //获取用户信息
        return getWXUserInfoMsg(accessToken,openid);
    }

    /**
     * 请求用户信息
     * @param accessToken
     * @param openid
     * @return
     */
    private WX_Dto getWXUserInfoMsg(String accessToken, String openid) {

        String param = "access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
        String requsetURL = WX_USERINFO_URL + "?" + param;

        //DONE:  2022/11/6 17:19 获取请求
        String response = HttpRequest.get(requsetURL).body();

        //DONE:  2022/11/6 17:24 json解析为json对
        JSONObject obj = JSON.parseObject(response);
        // TODO: 2022/11/10 调试
        log.info("第二步请求json："+response);

        //获取昵称还有头像路径
        Map<String,String> map = new HashMap();
        String headimgurl = (String)obj.get("headimgurl");
        String nickName = (String)obj.get("nickname");

        return WX_Dto
                .builder()
                .openid(openid)
                .avatar(headimgurl)
                .nickName(nickName)
                .build();
    }


}
